// src/utils/socket.ts
import type { ChatDataMessage, chatGroupMessage, sendGroupMessage, sendMessage } from '@/types/chat'
import { io, Socket } from 'socket.io-client'
const SOCKET_URL = 'http://localhost:3001' // 替换为你的 Socket 服务器地址

class SocketService {
  private static instance: SocketService | null = null // 单例实例
  private socket: Socket | null = null

  // 私有构造函数，防止外部直接实例化
  private constructor() {}

  // 获取单例实例
  public static getInstance(): SocketService {
    if (!SocketService.instance) {
      SocketService.instance = new SocketService()
    }
    return SocketService.instance
  }

  // 连接 Socket
  public connect(userId: string) {
    if (this.socket) {
      console.log('Socket is already connected')
      return
    }

    this.socket = io(SOCKET_URL, {
      query: { userId }
    })

    this.socket.on('connect', () => {
      console.log('Socket connected')
    })

    this.socket.on('disconnect', () => {
      console.log('Socket disconnected')
    })
  }

  // 监听消息
  public onMessage(callback: (message: ChatDataMessage) => void) {
    this.socket?.on('receivePrivateMessage', callback)
  }

  // 发送消息
  public sendMessage(message: sendMessage) {
    this.socket?.emit('sendPrivateMessage', message)
  }
  public onGroupMessage(callback: (message: chatGroupMessage) => void) {
    this.socket?.on('receiveGroupMessage', callback)
  }
  public sendGroupMessage(message: sendGroupMessage) {
    this.socket?.emit('sendGroupMessage', message)
  }
  // 断开连接
  public disconnect() {
    this.socket?.disconnect()
    this.socket = null
  }
}

// 导出单例实例
export const socketService = SocketService.getInstance()
